package com.codeduck.poi.controller.excel;

import com.codeduck.poi.util.AttachmentExportUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * @author: <a href="mailto:codeduck@163.com">Codeduck</a>
 * @date: 2023/2/12
 */
@RestController
public class MergeCellController {

    @GetMapping("merge/cells")
    public void mergeCellsTest(HttpServletResponse response) {

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("sheet1");
        initializesHeadRow(sheet);
        AttachmentExportUtil.export(workbook, "mergeCellsTest", response);
    }


    /**
     * 初始化Excel首行
     */
    private void initializesHeadRow(Sheet sheet) {
        if (sheet == null) {
            return;
        }

        // 单元格样式创建
        CellStyle cellStyle = sheet.getWorkbook().createCellStyle();
        //垂直居中
        cellStyle.setVerticalAlignment(cellStyle.getVerticalAlignmentEnum().CENTER);
        // 水平居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER_SELECTION);

        // 合并单元格并初始化值
        mergeCell(sheet, cellStyle, 0, 1, 0, 0, "RANK");
        mergeCell(sheet, cellStyle, 0, 1, 1, 1, "Country");

        mergeCell(sheet, cellStyle, 0, 0, 2, 3, "Population");
        mergeCell(sheet, cellStyle, 1, 1, 2, 2, "Numbers");
        mergeCell(sheet, cellStyle, 1, 1, 3, 3, "% of the world");

        mergeCell(sheet, cellStyle, 0, 1, 4, 4, "Date");
        mergeCell(sheet, cellStyle, 0, 1, 5, 5, "Source");
        mergeCell(sheet, cellStyle, 0, 1, 6, 6, "Notes");

    }


    /**
     * 合并单元格并初始化
     */
    private void mergeCell(Sheet sheet, CellStyle cellStyle, int firstRow, int lastRow, int firstCol, int lastCol, String val) {
        if (lastRow < firstRow || lastCol < firstCol) {
            return;
        }
        // 设置初始值
        setCellData(sheet, cellStyle, firstRow, firstCol, val);
        // 合并cell
        if (firstRow != lastRow || firstCol != lastCol) {
            sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol));
        }
    }

    /**
     * 单元格赋值并设置样式
     */
    private static void setCellData(Sheet sheet, CellStyle cellStyle, int firstRow, int firstCol, String val) {
        if (sheet == null) return;

        // 初始化cell
        if (sheet.getRow(firstRow) == null) {
            sheet.createRow(firstRow);
        }
        Row row = sheet.getRow(firstRow);
        Cell cell = row.createCell(firstCol);
        // 设置样式
        cell.setCellStyle(cellStyle);
        // 设置value
        cell.setCellValue(val);
        // 根据标题设置单元格宽度
        sheet.setColumnWidth(firstCol, cell.getStringCellValue().length() * 256 * 2);
    }

}
